package com.iwhalecloud.citybrain.flow.platform.manager.domain.validate;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;

/**
 * 校验表单控件编码是否唯一
 *
 * @author lilh
 * @date 2021/4/22 11:23
 */
public class FormComponentCodeUniqueCheckValidator implements ConstraintValidator<FormComponentCodeUniqueCheck, Object> {

    @Override
    public void initialize(FormComponentCodeUniqueCheck constraintAnnotation) {
        //可以获取注解上配置的所有信息
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        //执行校验逻辑
        if (Objects.isNull(value)) {
            return true;
        }
        String json = JSONObject.toJSONString(value);
        List<String> keys = JsonPath.read(json, "$..key");
        Set<String> setKeys = new HashSet<>(keys);
        //若没有重复，则size相等，反之，则有重复的key
        return keys.size() == setKeys.size();
    }
}
